package com.jumi.microservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.BaseController;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.RequestConstant;
import com.jumi.microservice.common.core.aspect.WebLog;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.domain.Log;
import com.jumi.microservice.domain.LogDetailVO;
import com.jumi.microservice.domain.OperateLogQuery;
import com.jumi.microservice.domain.Role;
import com.jumi.microservice.domain.dto.RoleDTO;
import com.jumi.microservice.domain.vo.RoleVO;
import com.jumi.microservice.service.LogService;
import com.jumi.microservice.service.RoleService;
import com.jumi.microservice.utils.LogObjectCopyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author liuz
 * @since 2020-07-18
 */
@RestController
@Api(tags = "角色表 相关接口")
@RequestMapping("/auth/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private LogService logService;

    @ApiOperation(value = "新增数据", notes = "新增一条角色表数据")
    @PostMapping("/add")
    @WebLog(description = "新增角色信息")
    public ResponseResult add(@Validated @RequestBody RoleVO vo, @RequestHeader(RequestConstant.ADMIN_NAME)String username) {
        //vo -> dto
        RoleDTO to = vo2Dto(vo);
        to.setCreater(username);
        to.setModifier(username);
        roleService.insert(to);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "删除数据", notes = "删除指定ID角色表数据")
    @ApiImplicitParam(name = "ids", value = "ids")
    @DeleteMapping("/delete")
    @WebLog(description = "删除角色信息")
    public ResponseResult delete(@RequestParam String ids, @RequestHeader(RequestConstant.ADMIN_NAME)String username) {
        roleService.delete(ids, username);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "更新数据", notes = "更新指定ID角色表数据")
    @PutMapping("/update")
    @WebLog(description = "更新角色信息")
    public ResponseResult update(@Validated @RequestBody RoleVO role, @RequestHeader(RequestConstant.ADMIN_NAME)String username) {
        //vo -> dto
        RoleDTO to = vo2Dto(role);
        to.setModifier(username);
        roleService.updateRole(to);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "查询数据", notes = "获取指定ID角色表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<RoleVO> detail(@RequestParam Long id) {
        RoleDTO role = roleService.selectById(id);
        return ResultGenerator.genSuccessResult(dto2Vo(role));
    }

    @ApiOperation(value = "启用/停用", notes = "角色状态的启用/停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID"),
            @ApiImplicitParam(name = "status", value = "状态")
    })
    @GetMapping("/enableStatus")
    @WebLog(description = "更新角色角色状态的启用/停用")
    public ResponseResult enableStatus(@RequestParam Long id, Integer status) {
        roleService.enableStatus(id,status);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "查询分页", notes = "获取角色表分页列表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页码"),
        @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/list")
    public BasePageResponse list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            RoleVO vo) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(vo.getRoleName()), Role::getRoleName,vo.getRoleName());
        wrapper.eq(vo.getId()!=null, Role::getId,vo.getId());
        wrapper.eq(vo.getStatus()!=null, Role::getStatus,vo.getStatus());
        wrapper.ge(StringUtils.isNotEmpty(vo.getStartTimeAdd()), Role::getCreateTime,vo.getStartTimeAdd());
        wrapper.le(StringUtils.isNotEmpty(vo.getEndTimeAdd()), Role::getCreateTime,vo.getEndTimeAdd());
        wrapper.ge(StringUtils.isNotEmpty(vo.getStartTimeUp()), Role::getUpdateTime,vo.getStartTimeUp());
        wrapper.le(StringUtils.isNotEmpty(vo.getEndTimeUp()), Role::getUpdateTime,vo.getEndTimeUp());
        wrapper.eq(Role::getIsDel,0);
        wrapper.orderByDesc(Role::getOrderNum, Role::getUpdateTime);
        IPage<Role> pageInfo = roleService.page(
                new Page<>(page, size),wrapper);
        return ResultGenerator.genSuccessResultPage(pos2Vos(pageInfo.getRecords()),pageInfo.getTotal());
    }

    @ApiOperation(value = "模块操作日志查询", notes = "模块操作日志查询分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码"),
            @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/listLog")
    public BasePageResponse listLog(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            OperateLogQuery logQuery) {
        Page<Log> list = logService.listOperateLogs(logQuery);
        //处理分页
//        if(list.size()>size){
//            return ResultGenerator.genSuccessResultPage(
//                    list.stream()
//                            .skip(size * (page - 1))
//                            .limit(size).collect(Collectors.toList())
//                    ,Long.valueOf(list.size()));
//        }
        return ResultGenerator.genSuccessResultPage(LogObjectCopyUtil.convertOperateLogDoList2VoList(list.getRecords()), list.getTotal());
    }

    /**
     * 对象转换 vo->dto
     * @param vo
     * @return
     */
    private RoleDTO vo2Dto(RoleVO vo){
        RoleDTO r = null;
        try {
            r = vo.clone(RoleDTO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return r;
    }

    /**
     * 对象转换 dto->vo
     * @param po
     * @return
     */
    private RoleVO dto2Vo(RoleDTO po){
        RoleVO r = null;
        try {
            r = po.clone(RoleVO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return r;
    }

    /**
     * 列表对象转换 po->vo
     * @param po
     * @return
     */
    private List<RoleVO> pos2Vos(List<Role> po){
        List<RoleVO> pos = po.stream().map(p-> {
            RoleVO vo = null;
            try {
                vo = p.clone(RoleVO.class);
            } catch (Exception e) {
                ExceptionEnum.FAIL_CHANGE.newException();
            }
            return vo;
        }).collect(Collectors.toList());
        return pos;
    }

//    /**
//     * 获取登录用户
//     * @param userId 主键id
//     * @return
//     */
//    private Account accountById(Long userId) {
//        AccountDTO ac = accountService.getAccountById(userId);
//        try {
//            return ac.clone(Account.class);
//        }catch (Exception e){
//
//        }
//        return null;
//    }

}
